package com.bys.util;

import cn.hutool.core.io.FileUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传工具类
 */
public class FileUtils {
    /**
     * 删除文件夹
     */
    public static  boolean deleteDir(File dir){
        boolean flag = false;
        int count = 0;
        if(!dir.exists()){
            flag =  true;
        }else{
            File[] files = dir.listFiles();
            if(files == null || files.length < 1){
                dir.delete();
                flag = true;
            }else{
                for (File file : files) {
                    if(file.isDirectory()){
                        deleteDir(file);
                    }else{
                        ++count;
                        file.delete();
                    }
                }
                // 将文件夹也删除
                if(count == files.length ){
                    dir.delete();
                    flag = true;
                }
            }
        }
        return flag;
    }

    public static boolean isImage(String fileName) {
        String extension = FileUtil.extName(fileName);
        return extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png") || extension.equals("gif");
    }
    public static boolean isVideoFile(String filePath) {
        File file = new File(filePath);
        String extension = getFileExtension(file.getName());
        // 判断常见视频文件的扩展名
        if (extension != null && (
                extension.equalsIgnoreCase("avi") ||
                        extension.equalsIgnoreCase("mp4") ||
                        extension.equalsIgnoreCase("mov") ||
                        extension.equalsIgnoreCase("mkv") ||
                        extension.equalsIgnoreCase("wmv"))) {
            return true;
        }

        // 如果扩展名无法识别，则尝试读取文件头部信息
        try {
            byte[] header = new byte[10];
            FileInputStream inputStream = new FileInputStream(file);
            inputStream.read(header);
            inputStream.close();

            // 根据文件头部信息判断是否为视频文件
            String fileHeader = bytesToHex(header);
            if (fileHeader.startsWith("000000146674797069736f6d")) { // 视频文件的十六进制文件头标识
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return false;
    }


    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex >= 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1).toLowerCase();
        }
        return null;
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

}

